import akshare as ak
import pandas as pd
import datetime
import os
import time


# 获取股票指定日期的数据 返回指定的字段 日期格式为字符串
def get_stock_data(stock_code, date_str, fields):
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=date_str, end_date=date_str,
                                            adjust="")
    if stock_zh_a_hist_df.empty:
        return None
    return stock_zh_a_hist_df.iloc[0][fields]


# 获取股票指定日期 11点半之前的成交量
def get_stock_volume_till_1130(stock_code, date_str):
    """
    获取指定股票在指定日期 9:30 - 11:30 的成交量总和
    :param stock_code: 股票代码（如 "000001"）
    :param date_str: 日期（如 "2024-03-20"）
    :return: 9:30 - 11:30 总成交量
    """
    start_time = f"{date_str} 09:30:00"
    end_time = f"{date_str} 11:30:00"

    # 获取分钟级别数据
    stock_minute_df = ak.stock_zh_a_hist_min_em(
        symbol=stock_code,
        start_date=start_time,
        end_date=end_time,
        period="1",  # 1 分钟K线
        adjust=""  # 不复权
    )

    if stock_minute_df.empty:
        return None

    # 计算 9:30 - 11:30 的成交量总和
    return stock_minute_df['成交量'].sum()


def get_stock_info_name(stock_code):
    stock_info = ak.stock_individual_info_em(symbol=stock_code)
    return stock_info.iloc[1]['value']


# 获取A股所有股票代码和名称
def get_all_stock_code():
    stock_zh_a_spot_df = ak.stock_zh_a_spot_em()
    return stock_zh_a_spot_df[['代码', '名称']].to_dict(orient="records")


def get_stock_volume_double(stock_code,date):
    dataObj={}
    # 需要的字段
    fields = ['日期', '成交量']
    # 日期字符串
    # 获取当前日期和时间
   

    date_str = date;
    # date_str = "20250321"
    # 前一天的总成交量
    pre_day_total_volume = 0
    # 当天11:30的总成交量
    total_volume_till_1130 = 0
    stock_name = get_stock_info_name(stock_code)
    print(f"股票名称:{stock_name}，股票代码:{stock_code}")
    # 获取前一天的日期
    # pre_date_str = datetime.datetime.strptime(date_str, "%Y%m%d") - datetime.timedelta(days=1)
    

    date_obj = datetime.datetime.strptime(date_str, "%Y%m%d")
    # 如果是周一则取上周五（减3天），否则正常取前一日
    if date_obj.weekday() == 0:  # 0代表周一
        pre_date_str = date_obj - datetime.timedelta(days=3)
    else:
        pre_date_str = date_obj - datetime.timedelta(days=1)
    pre_date_str = pre_date_str.strftime("%Y%m%d")



    
    # 获取股票指定日期的成交量
    stock_data = get_stock_data(stock_code, pre_date_str, fields)
    if stock_data is None:
        print("获取数据失败")
    else:
        stock_data['日期'] = stock_data['日期'].strftime('%Y-%m-%d')
        print(stock_data.to_dict()['日期'], stock_data.to_dict()['成交量'])
        pre_day_total_volume = stock_data.to_dict()['成交量']
    # 获取股票分时数据
    # 格式化日期为 2024-03-20
    date_str = datetime.datetime.strptime(date_str, "%Y%m%d").strftime("%Y-%m-%d")
    total_volume = get_stock_volume_till_1130(stock_code, date_str)
    if total_volume is None:
        print("获取数据失败")
    else:
        print(f"{date_str} 11:30总成交量", total_volume)
        total_volume_till_1130 = total_volume
    # 计算成交量是否大于前一天的2倍 并计算占比
    if total_volume_till_1130 > pre_day_total_volume * 2:
        print(f"{date_str} 11:30成交量大于前一天的2倍")
        if pre_day_total_volume!=0:
            print(f"占比为{total_volume_till_1130 / pre_day_total_volume * 100:.2f}%")
        # stock_code stock_name  total_volume_till_1130   pre_day_total_volume
        dataObj['代码'] = stock_code;
        dataObj['名称'] = stock_name;
        dataObj['今日成交'] = total_volume_till_1130;
        dataObj['昨日成交'] = pre_day_total_volume;

    else:
        print(f"{date_str} 11:30成交量小于前一天的2倍")
        if pre_day_total_volume!=0:
            print(f"占比为{total_volume_till_1130 / pre_day_total_volume * 100:.2f}%")

    print('-----------------------------------')
    return dataObj;



if __name__ == '__main__':

    # 读取stock_codes.csv文件 随机抽取50只股票代码
    stock_code_list = []
    with open('stock_codes.csv', 'r', encoding='UTF-8') as f:
        lines = f.readlines()
        for line in lines:
            stock_code_list.append(line.strip().split(',')[0])
            # 判断是否有50只股票代码
            if len(stock_code_list) == 5000:
                break

    info_list = []
    
    stock_code_list = ['300697']
    # current_date = datetime.datetime.now() - datetime.timedelta(days=3)
    current_date = datetime.datetime.now();

    for stock_code in stock_code_list:
        print(stock_code)
        infoObj = get_stock_volume_double(stock_code,current_date.strftime("%Y%m%d"));
        if len(infoObj)!=0:
            info_list.append(infoObj);
        
    df1 = pd.DataFrame(info_list)
    df1.to_excel('ex.xlsx', sheet_name='Sheet1', index=False) # index false为不写入索引

